﻿using System;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace Clipboard.Tools
{
    public class EmailHelper
    {
        // 邮件服务器配置
        private readonly string _smtpServer;
        private readonly int _smtpPort;
        private readonly bool _useSsl; // 添加一个布尔值来表示是否使用 SSL/TLS
        private readonly string _smtpUser;
        private readonly string _smtpPass;

        /// <summary>
        /// 初始化 EmailHelper 类
        /// </summary>
        /// <param name="smtpServer">SMTP 服务器地址</param>
        /// <param name="smtpPort">SMTP 服务器端口</param>
        /// <param name="smtpUser">SMTP 用户名</param>
        /// <param name="smtpPass">SMTP 密码</param>
        /// <param name="useSsl">是否使用 SSL/TLS</param>
        public EmailHelper(string smtpServer, int smtpPort, string smtpUser, string smtpPass, bool useSsl = true)
        {
            _smtpServer = smtpServer;
            _smtpPort = smtpPort;
            _useSsl = useSsl;
            _smtpUser = smtpUser;
            _smtpPass = smtpPass;
        }

        // 发送邮件的异步方法
        public async Task<bool> SendVerificationEmailAsync(string toEmail, string verificationCode)
        {
            try
            {
                // 创建邮件内容
                var message = new MimeMessage();
                message.From.Add(new MailboxAddress("Your App Name", _smtpUser)); // 发件人
                message.To.Add(new MailboxAddress("", toEmail)); // 收件人
                message.Subject = "邮箱验证"; // 邮件主题

                // 邮件正文内容
                var body = new TextPart("plain")
                {
                    Text = $"您的验证码是：{verificationCode}\n请在5分钟内完成验证。"
                };
                message.Body = body;

                // 创建 SMTP 客户端
                using (var client = new SmtpClient())
                {
                    // 连接到 SMTP 服务器
                    await client.ConnectAsync(_smtpServer, _smtpPort, _useSsl);
                    await client.AuthenticateAsync(_smtpUser, _smtpPass); // 登录SMTP服务器

                    // 发送邮件
                    await client.SendAsync(message);
                    await client.DisconnectAsync(true);
                }

                return true; // 成功发送
            }
            catch (Exception ex)
            {
                Console.WriteLine($"邮件发送失败: {ex.Message}");
                // 考虑记录到日志文件或通知相关人员
                return false; // 发送失败
            }
        }
    }
}